package logic

import (
	"context"
	"fmt"
	"retailers/model/mysql"
	"retailers/model/redis"
	"retailers/pkg"
	"retailers/retailersrpc/internal/svc"
	"retailers/retailersrpc/retailersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserloginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserloginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserloginLogic {
	return &UserloginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserloginLogic) Userlogin(in *retailersrpc.UserloginRequest) (*retailersrpc.UserloginResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("Captchalogin" + in.Phone)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("图形验证码错误请重新输入")
	}
	cmd := redis.Client.Get("sendSmslogin" + in.Phone)
	if cmd.Val() != in.Sms {
		return nil, fmt.Errorf("短信验证码输入错误请重新输入")
	}
	var finduser mysql.User
	mysql.DB.Debug().Where("phone= ?", in.Phone).Find(&finduser)
	if finduser.ID == 0 {
		return nil, fmt.Errorf("当前账号未被注册请重新输入")
	}
	if finduser.Password != pkg.Md5password(in.Password) {
		return nil, fmt.Errorf("当前密码不正确请重新输入")
	}
	mysql.DB.Debug().Create(&finduser)
	redis.Client.Del("Captchalogin" + in.Phone)
	redis.Client.Del("sendSmslogin" + in.Phone)
	return &retailersrpc.UserloginResponse{Id: int64(finduser.ID)}, nil
}
